<template>
	<div class="app-container" v-loading="loading" @contextmenu.prevent="">

		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="4">
						<el-tree-select  style="width: 100%;"
							placeholder="请选择所属公司" 
							v-model="queryParams.cid" 
							:data="baseConfigStore.newExCompanyList"
							:render-after-expand="false"
							 :default-expand-all="true" 
							 check-strictly clearable
							@node-click="nodeClickCompany" 
							@clear="nodeClearCompany">
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
					</el-col>
					<el-col :span="3">
						<el-select v-model="queryParams.sid" placeholder="请选择仓库"
							clearable>
							<el-option v-for="item in stockList" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入负责人姓名" clearable />
					</el-col>
					<el-col :span="7">
						<el-button :loading="loading" type="primary" @click="handleQuery">
							<template #icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn class="filtBox" @handleRefresh="resetQuery()" :strtype="strtype"></FilterColumn>
			</div>
		</div>



		<el-card shadow="never">
			
			
			<div class="action-row">
				<el-button v-hasPerm="['wms.Stocktaking/save']"   @click="handleDo('','act_add')" type="primary" plain><template #icon><i-ep-plus /></template>新增</el-button>
				<el-button v-hasPerm="['wms.Stocktaking/update']"  @click="handleDo('', 'act_edit')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-edit/></template>修改</el-button>
				<el-button v-hasPerm="['wms.Stocktaking/read']"  @click="handleDo('', 'act_read')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-Notification/></template>盘点数据</el-button>
			</div>

			<el-table ref="dataTableRef" 
				v-loading="loading" 
				:data="tableData" 
				align="left" 
				tooltip-effect="dark"
				:scrollbar-always-on="true" 
				 :show-overflow-tooltip="true" border
				@cell-mouse-enter="rowMouse"
				@cell-mouse-leave="menuLineVisible=false"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" align="center" width="55" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column :label="item.label" :align="item.align" :prop="item.prop" :width="item.width" :min-width="item.minwidth">
						<template #default="scope" v-if="item.prop == 'status'">
							<el-tag v-if="scope.row.status == 1" type="success">已完成</el-tag>
							<el-tag v-else-if="scope.row.status == 0" type="info">待盘点</el-tag>
						</template>
					</el-table-column>
				</template>
			</el-table>
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card>
		<!-- 新增内容 -->
		<el-dialog v-model="dialogAdd.visible" :close-on-click-modal="false" :close-on-press-escape="false"
			class="elDiaLog" lock-scroll :title="dialogAdd.title" width="1200px" @close="dialogAdd.visible = false">
			<el-form ref="dataFormRef" v-if="['act_add','act_edit'].includes(dialogAdd.status)" :model="formData" :rules="rules" v-loading="formloading"  label-width="130px">
			
			
				<el-form-item label="公司仓库" prop="cid">
					<el-tree-select  style="width: 100%;"
						placeholder="请选择所属公司" 
						v-model="formData.cid" 
						:data="baseConfigStore.newExCompanyList"
						:render-after-expand="false"
						 :default-expand-all="true" 
						 check-strictly 
						@node-click="nodeClick">
						<template v-slot:default="{node, data }">
							<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
						</template>
					</el-tree-select>
				</el-form-item>
			
				<el-form-item label="所属仓库" prop="sid">
					<el-select v-model="formData.sid" placeholder="请选择仓库"
						clearable>
						<el-option v-for="item in userStockList" :key="item.id" :label="item.name"
							:value="item.id" />
					</el-select>
				</el-form-item>
			

				<el-form-item label="负责人" prop="director">
					<el-select v-model="formData.director" placeholder="请选择负责人" style="width: 100%">
						<el-option v-for="(item, index) in userFList" :key="item.uid" :label="item.name"
							:value="item.uid">
							<treeBlock :dataItem="item" :typeClass="2"></treeBlock>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="盘点时间" prop="pd_time">
					<el-date-picker style="width: 100%;" placeholder="请输选择盘点时间" v-model="formData.pd_time"
						value-format="YYYY-MM-DD" type="date" />
				</el-form-item>
				<el-form-item label="备注" prop="mark">
					<el-input v-model="formData.mark" placeholder="请输入备注信息" show-word-limit rows="4" type="textarea" />
				</el-form-item>
			</el-form>
			
			<div v-loading="formloading" v-if="['act_read'].includes(dialogAdd.status)">
				<el-card style="margin-bottom: 30px;">
					<el-descriptions title="详情信息" direction="horizontal" :column="3">
						<el-descriptions-item width="30%" label="公司名称：">{{ pdData?.company.name}}</el-descriptions-item>
						<el-descriptions-item width="30%" label="仓库：">{{ pdData?.stockroom.name }}</el-descriptions-item>
						<el-descriptions-item width="30%" label="添加时间：">{{ pdData?.pd_time }} </el-descriptions-item>
							<el-descriptions-item width="30%" label="负责人：">{{ pdData?.director_info.name }}</el-descriptions-item>
						<el-descriptions-item width="30%" label="状态：">
							<el-tag v-if="pdData?.status == 1" type="success">已完成</el-tag>
							<el-tag v-else-if="pdData?.status == 0" type="info">待盘点</el-tag>
						</el-descriptions-item>
						<el-descriptions-item width="30%" ></el-descriptions-item>
						<el-descriptions-item :span="6" label="备注：">{{ pdData?.mark }}</el-descriptions-item>
					</el-descriptions>
				</el-card>
			
				<el-table ref="dataTableRef"  :data="pandianlist" align="left" :scrollbar-always-on="true"  tooltip-effect="dark" :show-overflow-tooltip="true"
					border size="small">
					
					<el-table-column type="index" label="序号" align="center" width="60" />
					<el-table-column label="仓位" min-width="150" align="center" prop="position.name"></el-table-column>
					
					<el-table-column label="图片" width="60" align="center" prop="goods.image">
						<template #default="scope">
							<el-image style="width: 35px; height: 35px" :src="scope.row.goods.image" :zoom-rate="1.2"
								:max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.goods.image]"
								:initial-index="0" fit="cover" />
						</template>
					</el-table-column>
					<el-table-column label="物品名称" min-width="140" align="center" prop="goods.name"></el-table-column>
					<el-table-column label="编码" min-width="140" align="center" prop="goods.sku"></el-table-column>
					<el-table-column label="品牌" min-width="140" align="center" prop="goods.brand"></el-table-column>
					<el-table-column label="规格型号" min-width="140" align="center" prop="goods.specs"></el-table-column>
					<el-table-column label="单位" min-width="100" align="center" prop="goods.unit"></el-table-column>
					<el-table-column label="备注" min-width="200" align="center" prop="goods.mark"></el-table-column>
					<el-table-column label="库存" width="120px" fixed="right" align="center" prop="stock"></el-table-column>
					<el-table-column label="盘后库存" width="120px" fixed="right" align="center" prop="counted_qty">
						<template #default="scope">
							<el-input-number style="width: 100%;" size="small" v-if="pdData.status==0" v-model="scope.row.counted_qty" :min="0" />
							<el-text size="small" v-else type="primary">{{scope.row.counted_qty}}</el-text>
						</template>
					</el-table-column>
					<el-table-column label="盘后差值" v-if="pdData?.status==1" width="120px" fixed="right" align="center"
						prop="counted_qty">
						<template #default="scope">
							<el-text size="small" v-if="scope.row.status == 1" type="danger"><i-ep-top width="15px" />{{scope.row.difference_qty}}</el-text>
							<el-text size="small" v-else-if="scope.row.status == 2"
								type="warning">
								<i-ep-Bottom width="15px" />{{scope.row.difference_qty}}</el-text>
							<el-text size="small" v-else-if="scope.row.status == 3"
								type="info">{{scope.row.difference_qty}}</el-text>
						</template>
					</el-table-column>
					<el-table-column label="是否同步库存" v-if="pdData?.status == 0" width="120px" fixed="right" align="center"
						prop="is_sync">
						<template #default="scope">
							<el-switch size="small" v-model="scope.row.is_sync" class="ml-2" />
						</template>
					</el-table-column>
			

					<el-table-column label="状态" fixed="right" width="120px" align="center" prop="status">
						<template #default="scope">
							<el-tag size="small" v-if="scope.row.status == 1" type="success">盘盈</el-tag>
							<el-tag size="small" v-else-if="scope.row.status == 2" type="warning">盘亏</el-tag>
							<el-tag size="small" v-else-if="scope.row.status == 3" type="primary">无差异</el-tag>
							<el-tag size="small" v-else type="info">待盘点</el-tag>
						</template>
					</el-table-column>
				</el-table>
			</div>
			
			
			<template #footer>
				<div class="dialog-footer">
					<el-button v-if="['act_add','act_edit'].includes(dialogAdd.status)" type="primary" @click="doData('act_submit')">确定</el-button>
					<el-button v-if="['act_read'].includes(dialogAdd.status) && pdData?.status == 0" type="primary"  @click="doData('act_check')">盘点</el-button>
					<el-button @click="dialogAdd.visible  = false">取消</el-button>
				</div>
			</template>
		</el-dialog>

		


	</div>
</template>
<script setup lang="ts">
	defineOptions({
		name: "Stockroom",
		inheritAttrs: false,
	});
	import { useRoute } from 'vue-router';
	//接口地址
	import {

		getStocktakingList,
		getStocktakingAdd,
		getStocktakingEdit,
		getStocktakingDetail,
		getStocktakingCheck,
		getStockroomSelectList
	} from "@/api/wms";
	//接口地址
	import {
		getUserOptions
	} from "@/api/engine";

	import { useTableFilterStore } from "@/store/modules/tableFilter";
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	const TableFilter = useTableFilterStore();
	const strtype = ref('vmsStocktaking')
	// 表格标题
	const cTitles = ["所属公司", "盘点仓库", "负责人", "状态", "备注", "盘点时间"];
	// 显示字段
	const sTitles = ["所属公司", "盘点仓库", "负责人", "状态", "备注", "盘点时间"];
	// 字段属性	
	const cColumns = [
		{ label: "所属公司", prop: "company.name", align: "center", minwidth: 200 },
		{ label: "盘点仓库", prop: "stockroom.name", align: "center", minwidth: 150 },
		{ label: "负责人", prop: "director_info.name", align: "center", minwidth: 150 },
		{ label: "状态", prop: "status", align: "center", minwidth: 150 },
		{ label: "备注", prop: "mark", align: "center", minwidth: 200 },
		{ label: "盘点时间", prop: "pd_time", align: "center", minwidth: 150 }
	]
	interface TableGlobalLocal {
		[key : string] : any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList() {
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if (ColumnsList) {
			const columnMap : any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {
				columnMap[column.label] = column;
			}
			const newList = [];
			for (const label of ColumnsList) {
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];
				if (foundColumn) {
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);
				}
			}
			return newList;
		}
		else {
			return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
		const dropColStr : string = strtype.value + '_dropCol';
		const checklistStr : string = strtype.value + '_checklist';
		const drop_col : any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
		const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr];
		if (!drop_col) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
		}
		if (!checklist) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
		}
	}



	
	const dataFormRef = ref(ElForm)
	const queryParamsData={
		page: 1,
		limit: 20,
		cid: "",//公司id
		sid: "",//仓库id
		name: ""//姓名
	}
	const formDataStaic={
		id: "",
		cid: "",//公司id
		sid: "",//仓库id
		director: "",//负责人
		pd_time: "",//盘点时间
		mark: ""//备注
	}
	//搜索-字段配置
	const queryParams = reactive(JSON.parse(JSON.stringify(queryParamsData)));
	const formData = ref<any>(JSON.parse(JSON.stringify(formDataStaic)))
	const loading = ref(false);
	const formloading = ref(false);//表单加载
	const total = ref(0);
	const tableData = ref();
	const multipleSelection = ref<any>([]);
	const menuLineVisible = ref(true);
	const rowR = ref<any>({});
	const pandianlist = ref();//盘点列表
	const pdData = ref<any>();//盘点数据
	const stockList = ref<any>();
	const userStockList:any = ref([]);
	const userFList : any = ref([]);
	const dialogAdd = reactive<any>({
		title: "", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status:"", //弹窗状态类型  :添加 add_art 编辑 edit_art 详情 detail_art  
		value:{}   		  //携带整条参数 row
	});

	const rules = reactive({
		cid:[{ required: true, message: "请选择所属公司", trigger: "change" }],
		sid: [{ required: true, message: "请选择公司仓库", trigger: "change" }],
		director: [{ required: true, message: "请选择负责人", trigger: "change" }],
		pd_time: [{ required: true, message: "请选择盘点时间", trigger: "change" }],
	});

	// 行菜单事件
	function rowMouse(row : any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val : any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val : number) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}

	// 操作
	 function handleDo(row:any, act:string) {
		 let  uItem:any= {}
		dialogAdd.status = act
		switch (act) {
			case 'act_add':
				dialogAdd.visible = true;
				dialogAdd.title="新增盘数据"
				formData.value = JSON.parse(JSON.stringify(formDataStaic));
				dataFormRef.value.clearValidate();
				break
			case 'act_edit':
				dialogAdd.visible = true;
				dialogAdd.title="修改盘点数据"
			
				uItem = JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				getUserOpti(uItem.cid)
				formData.value = uItem;
				break
			case 'act_read':
				dialogAdd.visible = true;
				dialogAdd.title="盘点数据";
				uItem = JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				formloading.value = true;
				getStocktakingDetail({ id: uItem.id }).then((res) => {
					console.log(res)
					pandianlist.value = res.data.detail
					pdData.value = res.data;
					formloading.value = false;
				}).finally(() => {})
				
				break	
			case 'act_del':
				// handleDelete(JSON.parse(JSON.stringify(row || multipleSelection.value[0])))
				break
			default:	
		}
	}


	// 处理结果
	function doData(act:string){
		switch (act) {
		  case 'act_submit':
			handleSubmit();
		    break
		  case 'act_check':
			ElMessageBox.confirm("确定对当前库存进行盘点，盘点后不可修改?", "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				handlePandian();
			});
		    break
		  default:
			ElMessage.error('无效操作')
		}
		
	}
	// 提交数据 修改
	function handleSubmit() {
		dataFormRef.value.validate((valid : boolean) => {
			if (valid) {
				if (formData.value.id) {
					getStocktakingEdit(formData.value).then((res) => {
						ElMessage({
							message: res.msg,
							type: 'success',
						})
						dialogAdd.visible = false;
						handleQuery();
						
					}).finally(() => { })
				}
				else {
					getStocktakingAdd(formData.value).then((res) => {
						ElMessage({
							message: res.msg,
							type: 'success',
						})
						dialogAdd.visible = false;
						handleQuery();
					}).finally(() => { })
				}
			}
		})	
	}
	
	// 盘点数据
	function handlePandian() {
		const newData = pandianlist.value.map(item => {
			return {
				id: item.id,
				num: item.counted_qty,
				is_sync: item.is_sync ? true : false
			};
		});
		getStocktakingCheck({
			id: pdData.value.id,
			detail: newData
		}).then((res) => {
			dialogAdd.visible = false;
			handleQuery();
			ElMessage({
				message: res.msg,
				type: 'success',
			})
			
		}).finally(() => {})
	}


	//获取仓库信息列表
	function handleQuery() {
		loading.value = true;
		getStocktakingList(queryParams).then((res) => {
			console.log(res);
			tableData.value = res.data.list;
			total.value = res.data.count;
		}).finally(() => {
			loading.value = false;
		})
	}
	/**
	 * 重置查询
	 */
	function resetQuery() {
		handleQuery();
	}



	
	
	
	
	/**
	   * 获取仓库列表
	   *  */

	function nodeClick(a : any, b : any, c : any, d : any) {
		formData.value.cid = a.cid;
		formData.value.sid = "";
		getUserOpti(a.cid);
		
	}
	//获取负责人列表
	function getUserOpti(id : any) {
		formData.value.director = ""
		formloading.value = true;
		getUserOptions({ cid: id }).then((res) => {
			console.log(res);
			formloading.value = false;
			userFList.value = res.data;
		}).finally(() => { })
		
		getStockroomSelectList({ cid: id }).then((res) => {
			userStockList.value = res.data;
		}).finally(() => { })
	}

	
	// 选择公司id
	function nodeClickCompany(a : any, b : any, c : any, d : any) {
		queryParams.sid = "";
		initStockList(a.cid)
	}
	// 取消选择公司id
	function nodeClearCompany() {
		stockList.value = [];
		queryParams.sid = "";
	}
	/**获取仓库列表 */
	function initStockList(cid ?: number) {
		getStockroomSelectList({ cid: cid }).then((res) => {
			stockList.value = res.data;
		}).finally(() => { })
	}
	

	onMounted(() => {
	
		handleQuery();
		columnsInit();
	})
</script>



<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.min220 {
		width: 220px
	}
</style>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>